package me.tonywang.common.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.Collections;
import java.util.Properties;

/**
 * @className: AliOcrUtils
 * @description:
 * @author: WANGHUI
 * @createDate: 2018/5/18 16:39
 * @version: 1.0
 */
public class AliOcrUtils {

    public static MediaType APPLICATION_JSON = MediaType.parse("application/json; charset=utf-8");

    private static Properties res;

    private static String OCR_IDCARD_URL;

    private static String OCR_BANK_CARD_URL;

    private static String OCR_APPCODE;

    private static String CONFIG_FILE = "config.properties";

    static {
        res = PropertiesUtils.load(CONFIG_FILE);
        Assert.notNull(res, CONFIG_FILE + " NOT FOUND");
        OCR_IDCARD_URL = res.getProperty("ocr_idcard_url");
        OCR_BANK_CARD_URL = res.getProperty("ocr_bank_card_url");
        OCR_APPCODE = res.getProperty("ocr_appcode");
    }

    public static String orcIdCard(String side, String imgBase64) throws IOException {
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imgBase64);
        requestObj.put("configure", Collections.singletonMap("side", side));
        RequestBody body = RequestBody.create(APPLICATION_JSON, requestObj.toJSONString());
        Request request = new Request.Builder()
                .url(OCR_IDCARD_URL)
                .headers(Headers.of(Collections.singletonMap("Authorization", "APPCODE " + OCR_APPCODE)))
                .post(body)
                .build();
        Response response = new OkHttpClient().newCall(request).execute();
        String result = response.body().string();
        if (side.equals("face")) {
            result = result.replace("num", "identityCode").replace("sex", "gender").replace("birth", "birthday");
        } else {
            result = result.replace("start_date", "startDate").replace("end_date", "identityExpirationDate");
        }
        return result;
    }

    public static String ocrBankCardUrl(String imgBase64) throws IOException {

        String bodystr = "{ \"inputs\": [  { \"image\": { \"dataType\": 50,   \"dataValue\": \"" + imgBase64 + "\" } }] }";
        RequestBody body = RequestBody.create(APPLICATION_JSON, bodystr);
        Request request = new Request.Builder()
                .url(OCR_BANK_CARD_URL)
                .headers(Headers.of(Collections.singletonMap("Authorization", "APPCODE " + OCR_APPCODE)))
                .post(body)
                .build();
        Response response = new OkHttpClient().newCall(request).execute();
        String result = response.body().string();
        String json = result.substring(result.indexOf("card_num") - 3, result.length() - 5).replace("\\", "").replace("card_num", "bankAccountNo");
        return json;
    }


}
